package controler;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import castleContent.User;
import dataBase.DataBase;
import dataBase.UpdateDBTables;

/**
 * Servlet implementation class ResourceServlet
 */
@WebServlet("/ResourceServlet")
public class ResourceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String resourceType = request.getParameter("resourceType");
		User user = (User) session.getAttribute("Object");
		try {
			goldMineUpgrades(resourceType, user);
			foodFarmUpgrades(resourceType, user);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		printResourceAndArmyCapacity(response, user);
	}

	private void goldMineUpgrades(String resourceType, User user)
			throws SQLException {

		if (user.castle.getGoldMine().getLevelUp() < 10
				&& user.castle.getGoldMine().getAvailableResource() >= 500) {
			if (resourceType.equals("goldMineProduction")) {
				user.castle.getGoldMine().levelUp();
				UpdateDBTables.updateGoldProduction(DataBase.getDbCon(), user
						.getName(), user.castle.getGoldMine().getProduction());
			}
		}
	}

	private void foodFarmUpgrades(String resourceType, User user) throws SQLException {
		if (user.castle.getFoodFarm().getLevelUp() < 10
				&& user.castle.getFoodFarm().getAvailableResource() >= 500) {
			if (resourceType.equals("foodHouseProduction")) {
				user.castle.getFoodFarm().levelUp();
				UpdateDBTables.updateFoodProduction(DataBase.getDbCon(), user
						.getName(), user.castle.getFoodFarm().getProduction());
			}
		}
	}

	private void printResourceAndArmyCapacity(HttpServletResponse response,
			User user) throws IOException {
		response.getWriter().print(
				"Food : " + user.castle.getFoodFarm().getAvailableResource()
						+ " Gold : "
						+ user.castle.getGoldMine().getAvailableResource()
						+ "<br>Army : "
						+ user.castle.getBarracks().getPresentArmy() + " / "
						+ user.castle.getBarracks().getArmyCapacity());
	}
}